package com.charmzenus.champion.utils;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.List;

public class FragmentUtils {

    /**
     * hide(..).show(..).commit(); 隐藏fragment 不重新初始化fragment
     * 通过fragment布局的id来显示下一个 fragmentLayoutId -- 布局 to -- 显示哪个fragment
     */
    public static synchronized void fragmentUse(int fragmentLayoutId,
                                                Fragment to, FragmentManager fm) {
        Fragment from = getVisibleFragment(fm); // 获取当前界面的fragment
        if (fm == null) return;

        FragmentTransaction transaction = fm.beginTransaction();

        if (from == null) {
            fm.beginTransaction().replace(fragmentLayoutId, to).commitAllowingStateLoss(); // 第一次没有来源的Fragment的时候，把这个Fragment当做来源
            return;
        }
        if (to == null) return;

        if (!to.isAdded()) {   // 先判断是否被add过
            transaction.hide(from).add(fragmentLayoutId, to).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
        } else {
            transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
        }
    }

    /**
     * 获取可见的fragment
     *
     * @param fm
     * @return
     */
    public static Fragment getVisibleFragment(FragmentManager fm) {

        if (fm == null) return null;
        List<Fragment> fragments = fm.getFragments();
        if (fragments == null || fragments.size() <= 0) return null;
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible()) return fragment;
        }
        return null;
    }

}
